import React from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  Alert,
} from 'react-native';

import BasePage from '../common/BasePage';
import TImage from '../../components/TImage';
import {DateUtils} from '../../utils/Utils';
import SizeUtils from '../../common/SizeUtils';
import ToastUtils from '../../common/ToastUtils';
import Config from '../../config';
import JifenMallPointAction from '../../actions/jifenmall/JifenMallPointAction';
import JifenMallRequestDuihuanItemDataAction from '../../actions/jifenmall/JifenMallRequestDuihuanItemDataAction';
import JifenMallSendBuyDuihuanItemAction from '../../actions/jifenmall/JifenMallSendBuyDuihuanItemAction';

export default class JifenDuihuanItemContentPage extends BasePage {
  constructor(props) {
    super(props);

    this._showImageWidth = SizeUtils.getWindowSize().width;
    this._showImageHeight = SizeUtils.getWindowSize().width / 751 * 422;
    this._headerHeight = SizeUtils.translateDesignHeightToCode(153);
    this._footerHeight = SizeUtils.translateDesignHeightToCode(120);
    this._contentHeight = SizeUtils.getWindowSize().height - Config.paddingTop -
      this._showImageHeight - this._headerHeight - this._footerHeight;

    this.state.itemData = this.props.pageData.routeData.itemData;
    this.state.lastDay = 0;
    this.state.lastHours = 0;
    this.state.statusText = "";
    this.state.buy_num = 1;
    this.isSend = false;

    this.state.jifenData = {point:{points:0}};
  }

  componentDidMount() {
    this._requestData();
  }

  componentWillUpdate(nextProps, nextState) {
    super.componentWillUpdate(nextProps, nextState);

    if(nextState.isResponeUpdate === true) {
      nextState.isResponeUpdate = false;
      this._calculateTime();
    }
    if(nextState.isUpdateByBuyItem === true) {
      nextState.isUpdateByBuyItem = false;
      this.isSend = false;
      //有错误信息
      if(nextState.statusText != "") {
        ToastUtils.show(nextState.statusText);
        nextState.statusText = "";
        this._requestData();
      }
      else {
        this.gotoPage(Config.pages.jifenmall_duihuan_result, {itemData:this._getItemData()});
      }
    }
    if(nextState.jifenData === null || nextState.jifenData === undefined) {
      nextState.jifenData = {point:{points:0}};
    }
  }

  _dealEnterPage() {
    super._dealEnterPage();
    this.state.itemData = this.props.pageData.routeData.itemData;
    this.state.lastDay = 0;
    this.state.lastHours = 0;
    this.state.buy_num = 1;
    this._requestData();
  }

  _requestData() {
    new JifenMallRequestDuihuanItemDataAction().call(this, this.props.pageData.routeData.itemData);
    new JifenMallPointAction().call(this);
  }

  render() {
    if(this.state.leave == true) {
      return this._renderEmptyView();
    }
    return (
      <View style={{width:SizeUtils.getWindowSize().width,
          height:SizeUtils.getWindowSize().height, backgroundColor:"#ffffff"}}>
        <View style={{width:SizeUtils.getWindowSize().width,
            height:SizeUtils.getWindowSize().height - this._footerHeight,
            paddingTop:Config.paddingTop}}>
          {this._renderShowImage()}
          {this._renderHeader()}
          {this._renderContent()}
        </View>
        {this._renderNavigationBar()}
        {this._renderFooter()}
      </View>
    )
  }

  _renderShowImage() {
    return (
      <View style={{}}>
        <TImage style={{width:this._showImageWidth,
          height:this._showImageHeight}} source={{uri:this._getItemData().image_url}}
          translatedSize={true}/>
      </View>
    )
  }

  _renderHeader() {
    return (
      <View style={{width:SizeUtils.getWindowSize().width,
          height:this._headerHeight, backgroundColor:"#ffffff",
          paddingLeft:SizeUtils.translateDesignWidthToCode(40),
          paddingRight:SizeUtils.translateDesignWidthToCode(40),
          flexDirection:"row", justifyContent:"space-between", alignItems:"center",
          borderColor:"#eeeeee", borderBottomWidth:SizeUtils.translateDesignNumToCode(3)}}>
          <View style={{height:this._headerHeight, paddingTop:SizeUtils.translateDesignHeightToCode(30),
              flexDirection:"column",}}>
            <View style={{flexDirection:"row", alignItems:"center"}}>
              <Text style={{fontSize:SizeUtils.translateFontSizeToCode(36)}}>
                {this._getItemData().name}
              </Text>
              <Text style={{fontSize:SizeUtils.translateFontSizeToCode(26),
                  color:"#999999", paddingLeft:SizeUtils.translateDesignWidthToCode(28)}}>
                还剩{this._getItemData().total - this._getItemData().buy_num}件
              </Text>
            </View>
            <View style={{flexDirection:"row", paddingTop:SizeUtils.translateDesignHeightToCode(10),
                alignItems:"center"}}>
              <Text style={{color:"#999999", fontSize:SizeUtils.translateFontSizeToCode(26)}}>
                {"距离结束 "}
              </Text>
              <Text style={{color:"#ffffff", backgroundColor:"#aaaaaa",
                  fontSize:SizeUtils.translateFontSizeToCode(30)}}>
                {" " + this.state.lastDay + " "}
              </Text>
              <Text style={{color:"#999999", fontSize:SizeUtils.translateFontSizeToCode(26)}}>
                {" 天 "}
              </Text>
              <Text style={{color:"#ffffff", backgroundColor:"#aaaaaa",
                  fontSize:SizeUtils.translateFontSizeToCode(30)}}>
                {" " + this.state.lastHours + " "}
              </Text>
              <Text style={{color:"#999999", fontSize:SizeUtils.translateFontSizeToCode(26)}}>
                {" 小时"}
              </Text>
            </View>
          </View>
          <View style={{width:SizeUtils.translateDesignWidthToCode(193),
              height:SizeUtils.translateDesignHeightToCode(100),
              flexDirection:"row", alignItems:"center", justifyContent:"center",
              borderColor:"#eeeeee", borderLeftWidth:SizeUtils.translateDesignNumToCode(3)}}>
            <Text style={{color:"#db3132", fontSize:SizeUtils.translateFontSizeToCode(40)}}>
              {this._getItemData().price} 积分
            </Text>
          </View>
      </View>
    )
  }

  _renderContent() {
    return (
      <ScrollView style={{paddingLeft:SizeUtils.translateDesignWidthToCode(40),
          width:SizeUtils.getWindowSize().width,
          height:this._contentHeight}}>
        <Text style={{paddingTop:SizeUtils.translateDesignHeightToCode(39),
            fontSize:SizeUtils.translateFontSizeToCode(32)}}>
          商品简介
        </Text>
        <Text style={{paddingTop:SizeUtils.translateDesignHeightToCode(33),
            fontSize:SizeUtils.translateFontSizeToCode(28), lineHeight:SizeUtils.translateDesignHeightToCode(40)}}>
          {this._getItemData().desc}
        </Text>
      </ScrollView>
    )
  }

  _renderFooter() {
    return (
      <View style={{width:SizeUtils.getWindowSize().width,
        height:this._footerHeight, position:"absolute", bottom:0,
        borderColor:"#eeeeee", borderTopWidth:SizeUtils.translateDesignNumToCode(3),
        paddingLeft:SizeUtils.translateDesignWidthToCode(20),
        paddingRight:SizeUtils.translateDesignWidthToCode(20),
        backgroundColor:"#ffffff", flexDirection:"row", alignItems:"center",
        justifyContent:"space-between"}}>
        <View style={{flexDirection:"row", alignItems:"center"}}>
          <Text style={{color:"#999999", fontSize:SizeUtils.translateFontSizeToCode(36)}}>
            数量
          </Text>
          {this._renderPagerBtn()}
        </View>
        {this._renderBuyButton()}
      </View>
    )
  }

  _renderPagerBtn() {
    return (
      <View style={{borderRadius:SizeUtils.translateDesignNumToCode(10),
        borderWidth:SizeUtils.translateDesignNumToCode(3), marginLeft:SizeUtils.translateDesignWidthToCode(10),
        borderColor:"#eeeeee", flexDirection:"row", alignItems:"center"}}>
        <TouchableOpacity style={{width:SizeUtils.translateDesignWidthToCode(55),
            height:SizeUtils.translateDesignHeightToCode(55), backgroundColor:"#00000000",
            flexDirection:"row", alignItems:"center", justifyContent:"center"}}
            onPress={this._onPressRelease.bind(this)}>
          <Text style={{backgroundColor:"#00000000", textAlign:"center",
              fontSize:SizeUtils.translateFontSizeToCode(40)}}>
            -
          </Text>
        </TouchableOpacity>
        <View style={{width:SizeUtils.translateDesignWidthToCode(85),
            height:SizeUtils.translateDesignHeightToCode(55), backgroundColor:"#00000000",
            borderColor:"#eeeeee", borderLeftWidth:SizeUtils.translateDesignNumToCode(3),
            borderRightWidth:SizeUtils.translateDesignNumToCode(3),
            flexDirection:"row", alignItems:"center", justifyContent:"center"}}>
          <Text style={{backgroundColor:"#00000000", textAlign:"center",
              fontSize:SizeUtils.translateFontSizeToCode(30),}}>
            {this.state.buy_num}
          </Text>
        </View>
        <TouchableOpacity style={{width:SizeUtils.translateDesignWidthToCode(55),
            height:SizeUtils.translateDesignHeightToCode(55), backgroundColor:"#00000000",
            flexDirection:"row", alignItems:"center", justifyContent:"center"}}
            onPress={this._onPressPlus.bind(this)}>
          <Text style={{backgroundColor:"#00000000", textAlign:"center",
              fontSize:SizeUtils.translateFontSizeToCode(40),
            }}>
            +
          </Text>
        </TouchableOpacity>
      </View>
    )
  }

  _onPressRelease() {
    let num = this.state.buy_num;
    num--;
    this.setState({
      buy_num:this._checkNumLegal(num),
    })
  }

  _onPressPlus() {
    let num = this.state.buy_num;
    num++;
    this.setState({
      buy_num:this._checkNumLegal(num),
    })
  }

  _checkNumLegal(num) {
    if(num < 1) {
      num = 1;
    }
    let maxNum = this._getItemData().total - this._getItemData().buy_num;
    if(num > maxNum) {
      num = maxNum;
    }
    return num;
  }

  _renderBuyButton() {
    return (
      <View style={{flexDirection:"row", alignItems:"center"}}>
        <Text style={{fontSize:SizeUtils.translateFontSizeToCode(26),
            paddingRight:SizeUtils.translateDesignWidthToCode(10), color:"#999999"}}>
          还能兑换{this.state.itemData.buy_left_num ? this.state.itemData.buy_left_num : 0}个
        </Text>
        <TouchableOpacity style={{borderRadius:SizeUtils.translateDesignNumToCode(20),
          backgroundColor:"#db3132", width:SizeUtils.translateDesignWidthToCode(210),
          height:SizeUtils.translateDesignHeightToCode(74), flexDirection:"row",
            alignItems:"center", justifyContent:"center"}}
          onPress={this._onPressBuyButton.bind(this)}
          disable={this._checkBuyButtonDisable.bind(this)}>
          <Text style={{color:"#ffffff", fontSize:SizeUtils.translateFontSizeToCode(36),
              textAlign:"center"}}>
            立即兑换
          </Text>
        </TouchableOpacity>
      </View>
    )
  }

  _checkBuyButtonDisable() {
    let maxNum = this._getItemData().total - this._getItemData().buy_num;
    if(maxNum < this.state.buy_num || maxNum <= 0) {
      return true;
    }
    return false;
  }

  _onPressBuyButton() {
    let result = this._checkBuyButtonDisable();
    if(result === true) {
      ToastUtils.show("物品存货不足,无法购买");
      return;
    }
    let needCost = this.state.buy_num * this.state.itemData.price;
    //积分不足
    if(needCost > this.state.jifenData.point.points) {
      ToastUtils.show("积分不足,无法购买");
      return;
    }

    if(this.state.itemData != null && this.state.itemData.buy_left_num != undefined)
    {
      if(this.state.itemData.buy_left_num < this.state.buy_num)
      {
        ToastUtils.show("兑换次数不足");
        return;
      }
    }

    Alert.alert('提示','确定花费' + needCost + "积分购买此商品?",[
        {text:'确定',onPress:()=>{
          ToastUtils.show("请求已发送...");
          if(this.isSend){
            return;
          }
          this.isSend = true;

          new JifenMallSendBuyDuihuanItemAction().call(this, {item_id:this._getItemData().item_id, buy_num:this.state.buy_num});
        }},
        {text:'考虑考虑',onPress:()=>{}},
      ])
  }

  _getItemData() {
    return this.state.itemData;
  }

  _calculateTime() {
    let beginTime = DateUtils.getDate(this._getItemData().buy_begin_at);
    let endTime = DateUtils.getDate(this._getItemData().buy_end_at);
    let lastDay = endTime.day - beginTime.day;
    let lastHours = beginTime.hours - endTime.hours;
    this.setState({
      lastDay:lastDay,
      lastHours:lastHours,
    })
  }
}
